from pyecharts import options as opts
from pyecharts.charts import Timeline, Line
from pyecharts.globals import ThemeType
import pandas as pd
import json

def get_model_trend_timeline(df):
    try:
        # 按年份和车型分组，计算每年各车型的总销量
        # 字段映射统一
        df = df.rename(columns={
            '年份': 'year',
            '月份': 'month',
            '销量': 'sales_volume',
            '车型': 'model',
            '厂商': 'manufacturer'
        })

        # 按年份和车型分组，计算每年各车型的总销量
        yearly_model_sales = df.groupby(['year', 'model'])['sales_volume'].sum().reset_index()
        
        # 创建一个空字典来存储每年销量前十的车型
        top_models_per_year = {}
        
        # 遍历每一年，找出销量前十的车型
        for year in yearly_model_sales['year'].unique():
            year_data = yearly_model_sales[yearly_model_sales['year'] == year]
            top_models = year_data.nlargest(10, 'sales_volume')['model'].tolist()
            top_models_per_year[year] = top_models
        
        # 获取所有年份并排序
        years = sorted(yearly_model_sales['year'].unique())
        
        # 创建时间轴对象
        timeline = Timeline(
            init_opts=opts.InitOpts(
                theme=ThemeType.LIGHT,
                width="1200px",
                height="750px",
                bg_color="#FFFFFF"
            )
        )
        
        # 遍历每个年份，生成对应的面积图
        for year in years:
            top_models = top_models_per_year[year]
            top_yearly_sales = yearly_model_sales[
                yearly_model_sales['model'].isin(top_models) & (yearly_model_sales['year'] <= year)]
            pivot_data = top_yearly_sales.pivot(index='year', columns='model', values='sales_volume').fillna(0)
            
            line = Line(
                init_opts=opts.InitOpts(width="1200px", height="700px")
            )
            line.add_xaxis(pivot_data.index.astype(str).tolist())
            
            # 为每个车型添加数据系列
            for idx, model in enumerate(pivot_data.columns):
                line.add_yaxis(
                    series_name=model,
                    y_axis=pivot_data[model].tolist(),
                    areastyle_opts=opts.AreaStyleOpts(opacity=0.4),
                    symbol_size=8,
                    label_opts=opts.LabelOpts(is_show=False),
                    is_smooth=True,
                    stack="总量",
                    linestyle_opts=opts.LineStyleOpts(width=2.5)
                )
            
            # 设置全局选项
            line.set_global_opts(
                title_opts=opts.TitleOpts(
                    title=f"截至{year}年销量前十车型销量趋势",
                    pos_left="center",
                    pos_top="5px",
                    title_textstyle_opts=opts.TextStyleOpts(font_size=20)
                ),
                tooltip_opts=opts.TooltipOpts(
                    trigger="axis",
                    axis_pointer_type="cross"
                ),
                xaxis_opts=opts.AxisOpts(
                    name="年份",
                    axislabel_opts=opts.LabelOpts(rotate=0),
                    splitline_opts=opts.SplitLineOpts(
                        is_show=True,
                        linestyle_opts=opts.LineStyleOpts(
                            width=1.5,
                            type_="dashed",
                            color="#e0e0e0"
                        )
                    )
                ),
                yaxis_opts=opts.AxisOpts(
                    name="年销量",
                    axislabel_opts=opts.LabelOpts(formatter="{value} 辆"),
                    splitline_opts=opts.SplitLineOpts(
                        is_show=True,
                        linestyle_opts=opts.LineStyleOpts(
                            width=1.5,
                            type_="dashed",
                            color="#e0e0e0"
                        )
                    )
                ),
                toolbox_opts=opts.ToolboxOpts(
                    is_show=True,
                    feature={
                        "saveAsImage": {},
                        "dataView": {},
                        "restore": {},
                        "dataZoom": {}
                    }
                ),
                legend_opts=opts.LegendOpts(
                    is_show=True,
                    type_="scroll",
                    orient="vertical",
                    pos_right="10px",
                    pos_top="50px",
                    item_width=12,
                    item_height=12,
                    textstyle_opts=opts.TextStyleOpts(font_size=12)
                )
            )
            
            # 添加到时间轴
            timeline.add(line, time_point=str(year))
        
        # 设置时间轴播放选项
        timeline.add_schema(
            is_auto_play=True,
            play_interval=3000,
            is_loop_play=True,
            is_timeline_show=True,
            orient="horizontal",
            pos_left="20%",
            pos_right="20%",
            pos_bottom="0px",
            width="60%",
            symbol_size=10,
            label_opts=opts.LabelOpts(font_size=12, color="#333"),
            linestyle_opts=opts.LineStyleOpts(width=2)
        )
        
        # 生成图表配置
        chart_config = timeline.dump_options()
        chart_config = json.loads(chart_config)  # 转换为Python字典
        
        return {
            'success': True,
            'chart_data': json.dumps(chart_config)  # 重新序列化为字符串
        }
        
    except Exception as e:
        return {
            'success': False,
            'error': f'处理数据时出错: {str(e)}'
        }